import { defineStore  } from 'pinia'
import { ref } from 'vue'
import { getCartList } from '../model/carts'

interface ResponseInfo {
  code: string,
  [key: string]: any
}

const useUserStore = defineStore('user', () => {
  const is_login = ref<boolean>(false)
  const cartList = ref([])

  const userid: string = window.localStorage.getItem('user_id') || ''

  async function fn () {
    // 判断一下, 如果没有 userid 表示肯定没有登录过
    if (!userid) return

    // 发送请求, 请求购物车数据
    const res = await getCartList(userid)
    if ((res as unknown as ResponseInfo).code === '200' || (res as unknown as ResponseInfo).code === '10020') {
      is_login.value = true
      cartList.value = res.data || []
    } else {
      is_login.value = false
    }
  }

  return {
    is_login,
    fn,
    cartList
  }
})

export default useUserStore
